package cn.silver.module.oss.service.impl;

import cn.silver.framework.core.constant.CacheNames;
import cn.silver.framework.core.enums.SystemStatusEnums;
import cn.silver.framework.core.utils.StreamUtils;
import cn.silver.framework.mybatis.service.impl.BusServiceImpl;
import cn.silver.framework.oss.constant.OssConstant;
import cn.silver.framework.redis.utils.RedisUtils;
import cn.silver.framework.tenant.domain.TenantEntity;
import cn.silver.framework.tenant.helper.TenantHelper;
import cn.silver.module.oss.bean.ConfigBean;
import cn.silver.module.oss.domain.OssConfig;
import cn.silver.module.oss.mapper.OssConfigMapper;
import cn.silver.module.oss.param.ConfigParam;
import cn.silver.module.oss.service.IOssConfigService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author zhouxiaobo
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OssConfigServiceImpl extends BusServiceImpl<OssConfigMapper, OssConfig, ConfigParam, ConfigBean> implements IOssConfigService {
    @Override
    public void init() {
        List<OssConfig> list = TenantHelper.ignore(() ->
                baseMapper.selectList(new LambdaQueryWrapper<OssConfig>().orderByAsc(TenantEntity::getTenantId))
        );
        Map<String, List<OssConfig>> map = StreamUtils.groupByKey(list, OssConfig::getTenantId);
        try {
            for (String tenantId : map.keySet()) {
                TenantHelper.setDynamic(tenantId);
                // 加载OSS初始化配置
                for (OssConfig config : map.get(tenantId)) {
                    String configKey = config.getCode();
                    if (SystemStatusEnums.NORMAL.getCode().equalsIgnoreCase(config.getStatus())) {
                        RedisUtils.setCacheObject(OssConstant.DEFAULT_CONFIG_KEY, "default", configKey);
                    }
                    RedisUtils.setCacheObject(CacheNames.SYS_OSS_CONFIG, config.getCode(), config);
                }
            }
        } finally {
            TenantHelper.clearDynamic();
        }
    }
}
